<?php
/**
 * 云门店
 */

defined('IN_IA') or exit('Access Denied');
include("../addons/j_hmoney/include/fun/CLSS_jetsum.php");
include("../addons/j_hmoney/include/fun/jetsum_function.php");

class j_hmoneyModuleSite extends WeModuleSite {
	function __construct()
    {
        $isseting=pdo_fetchcolumn("SELECT count(*) FROM ".tablename('j_hmoney_systemsetting')." ");
        if(!$isseting){
            pdo_insert("j_hmoney_systemsetting",array("keycode"=>""));
        }
	}
	public function __mobile($f_name){
		global $_W,$_GPC;
		$cfg = $this->module['config'];
		$floder=$cfg['floder'] ? $cfg['floder']."/": "";
		$dir = "../addons/j_hmoney/include/mobile/".$floder;
		if(!is_dir($dir))message("行业皮肤缺失");
		include_once 'include/mobile/'.$floder.strtolower(substr($f_name,8)).'.php';
	}
	
	public function __web($f_name){
		global $_W,$_GPC;
		$cfg = $this->module['config'];
        if(!$cfg['floder']){
            echo "请参数设置！";
            exit;
        }
		$floder=$cfg['floder'] ? $cfg['floder']."/": "";
		$dir = "../addons/j_hmoney/include/web/".$floder;
		if(!is_dir($dir)){
			message("行业皮肤缺失");
		}
		include_once 'include/web/'.$floder.strtolower(substr($f_name,5)).'.php';
	}
	public function doMobileSoft() {
		global $_GPC, $_W;
        include_once 'include/mobile/soft.php';
	}
    public function doMobileApp() {
        global $_GPC, $_W;
        include_once 'include/mobile/app.php';
    }
    public function doMobileMembercard() {
        global $_GPC, $_W;
        include_once 'include/mobile/membercard.php';
    }
    public function doMobileJumptomembercard() {
        global $_GPC, $_W;
        $cfg = $this->module['config'];
        if(!$cfg['wxmembercard'])message("未设置会员卡");
        $openid=$_W["openid"];
        //$openid="oQIpjuCvygPJ8nweOf4espujXnWs";
        if(!$openid)message("请在微信端登陆");
        $cardno=$this->openid2cardcode($cfg['wxmembercard'],$openid);
        if(!$cardno){
            if($cfg["isgetmembercard"]){
                $cardArry = $this->getCardTicket($cfg['wxmembercard'],$openid);
            }else{
                message($cfg['getmembercardinfo']);
            }
        }else{
            $cardArry = $this->getCardTicket($cfg['wxmembercard'],$openid);
        }
        include $this->template('jumptomembercard');
    }

	public function doMobileAjax() {
		global $_GPC, $_W;
		$this->__mobile(__FUNCTION__);
	}
	public function doMobileLogin() {
		global $_GPC, $_W;
		$this->__mobile(__FUNCTION__);
	}
	public function doMobileLoginadmin() {
		global $_GPC, $_W;
		$this->__mobile(__FUNCTION__);
	}
	public function doMobileIndex() {
		global $_GPC, $_W;
		$this->__mobile(__FUNCTION__);
	}
	public function doMobileMember() {
		global $_GPC, $_W;
		$this->__mobile(__FUNCTION__);
	}
	public function doMobileGame() {
		global $_GPC, $_W;
		$this->__mobile(__FUNCTION__);
	}
	public function doMobilePrint() {
		$this->doMobilePrintdoc();
	}
	public function doMobilePrintdoc() {
		global $_GPC, $_W;
		$this->__mobile(__FUNCTION__);
	}
	public function doMobilePhone() {
		global $_GPC, $_W;
		$this->__mobile(__FUNCTION__);
	}
    public function doMobilePlaceorder() {
        global $_GPC, $_W;
        $this->__mobile(__FUNCTION__);
    }
    public function doMobileMembercardactive() {
        global $_GPC, $_W;
        $cardid=$_GPC["card_id"];
        $openid=$_GPC["openid"];
        $ticket=urldecode($_GPC["activate_ticket"]);
        if(!$cardid || !$openid || !$ticket)message("非法登入");
        $member=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_membercard')." WHERE openid=:b ",array(":b"=>$openid));
        if($member)message("您的申请已提交，请勿重复提交","","error");
        load()->func('communication');
        $acid=pdo_fetchcolumn("SELECT acid FROM ".tablename('account')." WHERE uniacid=:uniacid ",array(':uniacid'=>$_W['uniacid']));
        $acc = WeAccount::create($acid);
        $tokens=$acc->fetch_token();
        $data=array(
            "activate_ticket"=>$ticket,
        );
        $pageparama=urldecode(json_encode($data));
        $resp = ihttp_request("https://api.weixin.qq.com/card/membercard/activatetempinfo/get?access_token=".$tokens,$pageparama, "");
        $result=@json_decode($resp['content'],true);

        if($result['errcode'] || !isset($result['errcode']) || $result['errmsg']!="ok"){
            $tokens=$acc->fetch_token();
            $data2=array(
                "openid"=>$openid,
                "card_id"=>$cardid
            );
            $pageparama=urldecode(json_encode($data2));
            $resp = ihttp_request("https://api.weixin.qq.com/card/user/getcardlist?access_token=".$tokens,$pageparama, "");
            $result=@json_decode($resp['content'],true);
            if($result['errcode'] || !isset($result['errcode']) || $result['errmsg']!="ok")message($result['errmsg']);
            $code=$result["card_list"][0]["code"];
            if(!$code)message($result['没匹配会员卡']);
            $tokens=$acc->fetch_token();
            $data=array(
                "code"=>$code,
                "card_id"=>$cardid
            );
            $pageparama=urldecode(json_encode($data));
            $resp = ihttp_request("https://api.weixin.qq.com/card/membercard/userinfo/get?access_token=".$tokens,$pageparama, "");
            $result=@json_decode($resp['content'],true);
            if($result['errcode'] || !isset($result['errcode']) || $result['errmsg']!="ok")message($result['errmsg']);
            $insert=array(
                "weid"=>$_W['uniacid'],
                "realname"=>$result['nickname'],
                "openid"=>$openid,
            );
            pdo_insert("j_hmoney_membercard",$insert);
            message("您的资料已提交，我们将尽快审核","","success");
        }
        $info=$result["info"];
        $userdata=array();
        foreach($info["common_field_list"] as $row){
            switch($row["name"]){
                case "USER_FORM_INFO_FLAG_MOBILE":
                    $userdata["mobile"]=$row["value"];
                break;
                case "USER_FORM_INFO_FLAG_SEX":
                    if($row["value"]=="男"){
                        $userdata["sex"]=1;
                    }elseif($row["value"]=="女"){
                        $userdata["sex"]=2;
                    }else{
                        $userdata["sex"]=0;
                    }
                    break;
                case "USER_FORM_INFO_FLAG_NAME":
                    $userdata["realname"]=$row["value"];
                    break;
                case "USER_FORM_INFO_FLAG_BIRTHDAY":
                    $userdata["birdday"]=$row["value"];
                    break;
            }
        }
        foreach($info["custom_field_list"] as $row){
                $userdata[$row["name"]]=$row["value"];
        }
        $insert=array(
            "weid"=>$_W['uniacid'],
            "realname"=>$userdata['realname'],
            "mobile"=>$userdata['mobile'],
            "birdday"=>$userdata['birdday'],
            "sex"=>$userdata['sex'],
            "openid"=>$openid,
            "activetxt"=>iserializer($userdata)
        );
        pdo_insert("j_hmoney_membercard",$insert);
        message("您的资料已提交，我们将尽快审核","","success");
    }
    public function doMobileTest() {
        global $_GPC, $_W;
//        $cfg = $this->module['config'];
//        $cardid=$cfg["wxmembercard"];
//        $acid=pdo_fetchcolumn("SELECT acid FROM ".tablename('account')." WHERE uniacid=:uniacid ",array(':uniacid'=>$_W['uniacid']));
//        $acc = WeAccount::create($acid);
//        $tokens=$acc->fetch_token();
//        $pageparama=json_encode(array("card_id"=>$cardid));
//        $resp = ihttp_request("https://api.weixin.qq.com/card/delete?access_token=".$tokens,$pageparama, "");
//        $result=@json_decode($resp['content'],true);
//        var_dump($result);
    }

    public function wildDog_socket($shopid){
        $cfg = $this->module['config'];
        if(strlen($cfg['wilddog'])<10)return;
        $url=$cfg['wilddog']."/shopid/".$shopid."/.json";
        $headers = array(
            'Accept: application/json',
            'Content-Type: application/json',
        );
        $postdata = json_encode(array(strval($shopid)=>TIMESTAMP));
        $handle = curl_init();
        curl_setopt($handle, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($handle,CURLOPT_HEADER,1); // 是否显示返回的Header区域内容
        curl_setopt($handle, CURLOPT_HTTPHEADER, $headers); //设置请求头
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
        curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'PATCH');
        curl_setopt($handle, CURLOPT_POSTFIELDS, $postdata); //设置请求体，提交数据包
        $response = curl_exec($handle); // 执行操作
        curl_close ($handle); // 关闭CURL会话
        return $response;
    }

    public function doMobileAd() {
        global $_GPC, $_W;
        include_once 'include/mobile/ad.php';
    }

    public function doMobileUpdate() {
        global $_GPC, $_W;
        include_once 'include/mobile/update.php';
    }
    public function doMobileBankpaycallback() {
        global $_GPC, $_W;
        echo "success";
        die();
    }
	/**/

    public function doWebAjax() {
        global $_GPC, $_W;
        include_once 'include/web/ajax.php';
    }
	public function doWebLogin() {
		global $_GPC, $_W;
		$this->__web(__FUNCTION__);
	}
	public function doWebIndexs() {
		global $_GPC, $_W;
		$this->__web(__FUNCTION__);
	}
	public function doWebShop() {
		global $_GPC, $_W;
		$this->__web(__FUNCTION__);
	}
	public function doWebStaff() {
		global $_GPC, $_W;
		$this->__web(__FUNCTION__);
	}
	public function doWebGoods() {
		global $_GPC, $_W;
		$this->__web(__FUNCTION__);
	}
    public function doWebGoodspackage() {
        global $_GPC, $_W;
        include_once 'include/web/goodspackage.php';
    }
	public function doWebStore() {
		global $_GPC, $_W;
		$this->__web(__FUNCTION__);
	}
	public function doWebTable() {
		global $_GPC, $_W;
		$this->__web(__FUNCTION__);
	}
	public function doWebMember() {
		global $_GPC, $_W;
		$this->__web(__FUNCTION__);
	}
	public function doWebSettings() {
		global $_GPC, $_W;
		$this->__web(__FUNCTION__);
	}
	public function doWebLottery() {
		global $_GPC, $_W;
        include_once 'include/web/lottery.php';
	}
	public function doWebPrint() {
		global $_GPC, $_W;
		$this->__web(__FUNCTION__);
	}
	
	public function doWebSale() {
		global $_GPC, $_W;
		$this->__web(__FUNCTION__);
	}
	public function doWebSalemember() {
		global $_GPC, $_W;
		$this->__web(__FUNCTION__);
	}
	public function doWebSalegoods() {
		global $_GPC, $_W;
		$this->__web(__FUNCTION__);
	}
	public function doWebMarket() {
		global $_GPC, $_W;
		$this->__web(__FUNCTION__);
	}
    public function doWebAdmanage() {
        global $_GPC, $_W;
        include_once 'include/web/admanage.php';
    }
    public function doWebElem() {
        global $_GPC, $_W;
        include_once 'include/web/elem.php';
    }
    public function doWebProjects() {
        global $_GPC, $_W;
        $this->__web(__FUNCTION__);
    }

    public function doWebTimecard() {
        global $_GPC, $_W;
        $this->__web(__FUNCTION__);
    }


	public function openid2cardcode($cardid,$openid){
        global $_GPC, $_W;
        if(!$cardid || !$openid)return false;
        $acid=pdo_fetchcolumn("SELECT acid FROM ".tablename('account')." WHERE uniacid=:uniacid ",array(':uniacid'=>$_W['uniacid']));
        $acc = WeAccount::create($acid);
        $tokens=$acc->fetch_token();
        $pageparama=json_encode(array("openid"=>$openid,"card_id"=>$cardid));
        $resp = ihttp_request("https://api.weixin.qq.com/card/user/getcardlist?access_token=".$tokens,$pageparama, $xml);
        $result=@json_decode($resp['content'],true);
        if(!$result['errcode']){
            $card_list=$result['card_list'];
            return $card_list[0]["code"];
        }
        return false;
    }

	public function authcode2openid($qrcode='',$userid='',$flag=false){
		global $_GPC, $_W;
		if(!$qrcode)return false;
		if(!$userid){
			session_start();
			$shopid=$_SESSION['shopid'];
			if(!$shopid)return false;
			$shop=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_group')." WHERE weid='{$_W['uniacid']}' and id=:a ",array(":a"=>$shopid));
		}else{
			$user=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_user')." WHERE weid='{$_W['uniacid']}' and id=:a and status=1",array(":a"=>$userid));
			$shop=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_group')." WHERE weid='{$_W['uniacid']}' and id=:a ",array(":a"=>$user['pcate']));
		}
		load()->func('communication');
		$cfg = $this->module['config'];
		$payParama=array(
			"appid"=>$shop['appid'] ? $shop['appid'] : $cfg['appid'],
			"pay_mchid"=>strval($shop['pay_mchid']) ? strval($shop['pay_mchid']) : strval($cfg['pay_mchid']),
			"pay_signkey"=>$shop['pay_signkey'] ? $shop['pay_signkey'] : $cfg['pay_signkey'],
			"sub_appid"=>$shop['sub_appid'] ? $shop['sub_appid'] : $cfg['sub_appid'],
			"sub_mch_id"=>$shop['sub_mch_id'] ? $shop['sub_mch_id'] : $cfg['sub_mch_id'],
		);
		$pay_signkey=trim($shop['pay_signkey']) ? trim($shop['pay_signkey']) : trim($cfg['pay_signkey']);
		$pageparama=array(
			"appid"=>$shop['appid'] ? $shop['appid'] : $cfg['appid'],
			"mch_id"=>strval($shop['pay_mchid']) ? strval($shop['pay_mchid']) : strval($cfg['pay_mchid']),
			"auth_code"=>$qrcode,
			"nonce_str"=>getNonceStr(),
		);
		if($payParama['sub_appid'])$pageparama['sub_appid']=$payParama['sub_appid'];
		if($payParama['sub_mch_id'])$pageparama['sub_mch_id']=$payParama['sub_mch_id'];
		$sign=MakeSign($pageparama,$pay_signkey);
		$pageparama['sign']=$sign;
		$xml = ToXml($pageparama);
		$response =postXmlCurl($xml, "https://api.mch.weixin.qq.com/tools/authcodetoopenid", 10);
		$result=FromXml($response);
		if($result['return_code']=='SUCCESS' && $result['result_code']=='SUCCESS'){
			$openid=$result['openid'];
			load()->model('mc');
			$uid=mc_openid2uid($openid);
			$userinfo=mc_fetch($uid);
			$userinfo['openid']=$openid;
			return $userinfo;
		}
		return false;
	}

	public function cardcode2openid($cardid='',$code=''){
		global $_W;
		if(!$cardid)return false;
		if(!$code)return false;
		$acid=pdo_fetchcolumn("SELECT acid FROM ".tablename('account')." WHERE uniacid=:uniacid ",array(':uniacid'=>$_W['uniacid']));
		$acc = WeAccount::create($acid);
		$tokens=$acc->fetch_token();
		$url = "https://api.weixin.qq.com/card/code/get?access_token=".$tokens;
		$data=array(
			"card_id"=>$cardid,
			"code"=>$code,
		);
		$content = ihttp_post($url,json_encode($data));
		$result = @json_decode($content['content'], true);
		if($result['errcode'])return false;
		return $result['openid'];
	}
	
	public function findMarketing($fee=0,$shopid=0,$ftye=0,$memeberid=0){
		global $_W;
		if($fee<=0)return false;
		if(!$shopid)return false;
		$condition=$ftye ? " and ftype=".$ftye : "";
		$marketlist=pdo_fetchall("SELECT * FROM ".tablename('j_hmoney_marketing')." WHERE  weid = '{$_W['uniacid']}' and groupid=:a and fee*100<=:b and starttime<='".TIMESTAMP."' and endtime>='".TIMESTAMP."' and status=1 $condition order by displayorder asc",array(':a'=>$shopid,":b"=>$fee));
		if(!$marketlist)return false;
		$marketid=0;
		$marketItem=array();
		foreach($marketlist as $row){
			if(!$row['content'])continue;
			//会员等级判断
			if($row['memberlevel']){
				if(!$memeberid)continue;
				$mlevel=pdo_fetchcolumn("SELECT gid FROM ".tablename('j_hmoney_membercard')." WHERE id=:a ",array(":a"=>$memeberid));
				if(!in_array($mlevel,explode(',',$row['memberlevel'])))continue;
			}
			//星期判断
			if($row['limitweek']){
				$day=date('w') ? date('w') : 7;
				if(!in_array($day,explode(',',$row['limitweek'])))continue;
			}
			//时间段判断
			if($row['limithour']){
				$time=intval(date('h'));
				if(!in_array($time,explode(',',$row['limithour'])))continue;
			}
			$marketid=$row['id'];
			$marketItem=$row;
			break;
		}
		if(!$marketid)return false;
		$content=$marketItem['content'];
		$returnAry=array(
			"mid"=>$marketid,
			"ftype"=>$marketItem['ftype'],
			"content"=>$marketItem['content'],
		);
		//返回优惠计算
		switch($marketItem['ftype']){
			//满减
			case 1:
				$couponfee=0;
				if(strpos($content,"-")){
					$tempary=explode("-",$content);
					if(strpos($tempary[0],"%")){
						$temp1=mt_rand(str_replace("%","",$tempary[0]),str_replace("%","",$tempary[1]));
						$couponfee=intval($fee*(100-$temp1)*0.01);
					}else{
						$couponfee=$fee*(mt_rand(intval($tempary[0]*100),intval($tempary[1]*100)));
					}
				}else{
					if(strpos($content,"%")){
						$couponfee=intval($fee*(100-(str_replace("%","",$content)))*0.01);
					}else{
						$couponfee=intval($content*100);
					}
				}
				$returnAry['coupon']=intval($couponfee);
			break;
			//返卡券
			case 2:
				$temp=strpos($content,"|") ? explode("|",$content) : array($content);
				shuffle($temp);
				$cardkey=$temp[0];
				$returnAry['coupon']=$cardkey;
			break;
			//返红包
			case 3:
				$couponfee=0;
				if(strpos($content,"-")){
					$tempary=explode("-",$content);
					if(strpos($tempary[0],"%")){
						$couponfee=$fee*(mt_rand(str_replace("%","",$tempary[0]),str_replace("%","",$tempary[1]))*0.01);
					}else{
						$couponfee=$fee*(mt_rand(intval($tempary[0]*100),intval($tempary[1]*100)));
					}
				}else{
					if(strpos($content,"%")){
						$couponfee=$fee*(str_replace("%","",$content)*0.01);
					}else{
						$couponfee=$content*100;
					}
				}
				$returnAry['coupon']=intval($couponfee);
			break;
			//返抽奖次数
			case 4:
				$coupon=0;
				$returnAry['gameid']=$marketItem['gameid'];
				if(strpos($content,"|")){
					$temp=explode("|",$content);
					$coupon=$fee % intval($temp[0]*100)*$temp[1];
				}else{
					$coupon=intval($content);
				}
				$returnAry['coupon']=$coupon;
			break;
		}
		
		return $returnAry;
	}
	//核销卡券
	public function employCard($code="",$shopid=""){
		global $_W;
		if(!$code)return false;
		if(!$shopid)return false;
		load()->func('communication');
		$shop=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_group')." WHERE weid='{$_W['uniacid']}' and id=:a ",array(":a"=>$shopid));
		$acid=pdo_fetchcolumn("SELECT acid FROM ".tablename('account')." WHERE uniacid=:uniacid ",array(':uniacid'=>$_W['uniacid']));
		$acc = WeAccount::create($acid);
		$tokens=$acc->fetch_token();
		$pageparama=json_encode(array("code"=>$code));
		$resp = ihttp_request("https://api.weixin.qq.com/card/code/consume?access_token=".$tokens,$pageparama, $xml);
		if(is_error($resp)) {
			$procResult = $resp;
		}
		$arr=@json_decode($resp['content'],true);
		if($arr['errcode']){
			return array("success"=>false,"msg"=>"核销失败。失败原因：".implode(",",$arr));
		}
//		$cardid=$arr['card']['card_id'];
//		$openid=$arr['openid'];
//		if(!$cardid || !$openid)return array("success"=>false,"msg"=>"核销失败。失败原因：".implode(",",$arr));
		return array("success"=>true);
	}
	/*转移余额到微擎余额*/
	public function transferBalance($memberid=""){
		global $_W;
		if(!$memberid)return false;
		$cfg = $this->module['config'];
		if(!$cfg['isgeneralbalance'])return false;
		load()->model('mc');
		$member=pdo_fetch("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' and id=:a ",array(":a"=>$memberid));
		if(!$member['openid'])return false;
		$uid=mc_openid2uid($member['openid']);
		$cash=sprintf('%.2f',($member["cash"]*0.01));
		if($cash){
			mc_credit_update($uid,"credit2",$cash,array("","收银系统转移模块余额￥".$cash."元"));
			pdo_update("j_hmoney_membercard",array('cash'=>0),array("id"=>$member['id']));
		}
		return true;	
	}

	public function memberCardInform($memberid=""){
		global $_W;
		if(!$memberid)return false;
		$cfg = $this->module['config'];
		if(!$cfg['wxmembercard'])return false;
		$member=pdo_fetch("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' and id=:a ",array(":a"=>$memberid));
		if(!$member['openid'])return false;
		if(!$member['wxcardno'])return false;
		load()->model('mc');
		$uid=mc_openid2uid($member['openid']);
		$userinof=mc_fetch($uid);
		$cash=$member['cash'];
		$credit=$member['credit'];
		$menberGid=$member['gid'];
        if(!$member['uid'])pdo_update("j_hmoney_membercard",array("uid"=>$uid),array("id"=>$member['id']));
		if($credit*100>0)$flag=mc_credit_update($uid,"credit1",$member['credit'],array("","收银台消费积分转移"));
		if($flag)pdo_update("j_hmoney_membercard",array("credit"=>0),array("id"=>$member['id']));
		if($uid){
			$creditAry=mc_credit_fetch($uid,array('credit1'));
			$credit=$creditAry['credit1'];
			if($cfg['isgeneralbalance']){
				if($cash>0)$flag=mc_credit_update($uid,"credit2",sprintf('%.2f',($member['cash']*0.01)),array("","收银台消费余额转移"));
				if($flag)pdo_update("j_hmoney_membercard",array("cash"=>0),array("id"=>$member['id']));
				$creditAry2=mc_credit_fetch($uid,array('credit2'));
				$cash=intval($creditAry2['credit2']*100);
			}
			/*同步会员等级*/
            $gid=$member['gid'];
            foreach(mc_groups() as $row){
                if(intval($credit*100)>=intval($row['credit']*100)){
                    $gid=$row['groupid'];
                }
            }
			if($member['gid']!=$gid){
				$menberGid=$userinof['groupid'];
				pdo_update("j_hmoney_membercard",array("gid"=>$userinof['groupid']),array("id"=>$member['id']));
			}
		}
		$groupname=pdo_fetchcolumn("SELECT title FROM ".tablename("mc_groups")." WHERE uniacid='".$_W['uniacid']."' and groupid=:a",array(":a"=>$menberGid));
		if(!$groupname)$groupname="会员";
		load()->func('communication');
		$acid=pdo_fetchcolumn("SELECT acid FROM ".tablename('account')." WHERE uniacid=:uniacid ",array(':uniacid'=>$_W['uniacid']));
		$acc = WeAccount::create($acid);
		$tokens=$acc->fetch_token();
		$data=array(
			"card_id"=>$cfg['wxmembercard'],
			"code"=>$member['wxcardno'],
			"bonus"=>intval($credit),
			"custom_field_value1"=>strval(sprintf('%.2f',($cash*0.01))),
		);
		$pageparama=urldecode(json_encode($data));
		$resp = ihttp_request("https://api.weixin.qq.com/card/membercard/updateuser?access_token=".$tokens,$pageparama, $xml);
		$result=@json_decode($resp['content'],true);
	}
	/*生成营销二维码*/
	public function IncreateQrcode($outTradeNo,$type=0,$timers=7){
		global $_W;
		$timer = intval($timers);
		if($timer<1)$timer=1;
		if($timer>30)$timer=30;
		//
		if($type==1){
			$title="收银台礼品兑换";
			$giftrecord=pdo_fetch("SELECT * FROM " . tablename('j_hmoney_giftrecord') . " WHERE weid = '{$_W['uniacid']}' and out_trade_no=:a",array(":a"=>$outTradeNo));
			$rid=pdo_fetchcolumn("SELECT rid FROM " . tablename('j_hmoney_reply') . " WHERE weid = '{$_W['uniacid']}' and gtype=1 order by id desc limit 1");
			if(!$rid)return "";
			$keyword=pdo_fetchcolumn("SELECT content FROM " . tablename('rule_keyword') . " WHERE rid=:a",array(":a"=>$rid));
			$hash=$giftrecord['id'];
		}elseif($type==2){
			$title="收银台收银小票";
			$order=pdo_fetch("SELECT * FROM " . tablename('j_hmoney_order') . " WHERE weid = '{$_W['uniacid']}' and out_trade_no=:a",array(":a"=>$outTradeNo));
			$rid=pdo_fetchcolumn("SELECT rid FROM " . tablename('j_hmoney_reply') . " WHERE weid = '{$_W['uniacid']}' and gtype=2 order by id desc limit 1");
			if(!$rid)return "";
			$keyword=pdo_fetchcolumn("SELECT content FROM " . tablename('rule_keyword') . " WHERE rid=:a",array(":a"=>$rid));
			$hash=$order['id'];
		}
		$expire=86400*$timer;
		$barcode['expire_seconds']=$expire;
		$barcode['action_info']['scene']['scene_id'] = $hash;
		$barcode['action_name'] ='QR_SCENE';
		$uniacccount = WeAccount::create($_W['account']['acid']);
		$result = $uniacccount->barCodeCreateDisposable($barcode);
		if(!is_error($result)){
			$data2=array(
				'uniacid'=>$_W['uniacid'],
				'acid'=>$_W['account']['acid'],
				'name'=>$title,
				'keyword'=>$keyword,
				'model'=>1,
				'createtime'=>TIMESTAMP,
				'type'=>'scene',
				'status'=>1,
				'expire'=>$expire,
				'qrcid'=>$hash,
				'scene_str'=>$hash,
				'ticket'=>$result['ticket'],
				'url'=>$result['url'],
				'name'=>$title,
			);
			pdo_insert('qrcode', $data2);
		}
		return $result['url'];
	}
	
	public function fun_refunder($rtype,$orderid,$userid,$shopid,$remark="",$num=0,$rfee=0,$paytype=99,$isgetback=1){
		//'1订单，2商品，3茶位，4充值',
		global $_W;
		$cfg = $this->module['config'];
		$refun_out_no=TIMESTAMP.mt_rand(100,999);
		if($rtype==1){
			$order=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_order')." WHERE weid = '{$_W['uniacid']}' and id=:a",array(":a"=>$orderid));
			if($order['ispay']==0)return array("success"=>false,"msg"=>"订单状态异常");
			$datarefund=array(
				"weid"=>$_W['uniacid'],
				"userid"=>$userid,
				"groupid"=>$shopid,
				"paytype"=>$paytype,
				"rtype"=>1,
				"createtime"=>TIMESTAMP,
				"createdate"=>date("Y-m-d"),
				"out_trade_no"=>$order['out_trade_no'],
				"out_refund_no"=>$refun_out_no,
				"remark"=>"整单退款;".$remark,
				"fee"=>$order['paid_fee'],
				"orderid"=>$orderid,
				"num"=>$order['num']
			);
			pdo_insert("j_hmoney_refund",$datarefund);
			$refundid=pdo_insertid();
			if(!$refundid)return array("success"=>false,"msg"=>"生成退款单失败");
			$shop=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_group')." WHERE id =:a",array(":a"=>$shopid));
			$user=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_user') ." WHERE id =:a",array(":a"=>$userid));
			$mpaytype=$paytype;
			if($paytype==99){
				$mpaytype=$order["paytype"];
				pdo_update("j_hmoney_refund",array("paytype"=>$order["paytype"]),array("id"=>$refundid));
			}
			switch($mpaytype){
					case 2:
					case 3:
						pdo_update("j_hmoney_refund",array("status"=>1),array("id"=>$refundid));
					break;
					case 4:
						$memberno=$order['memberno'];
						$member=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_membercard')." WHERE weid = '{$_W['uniacid']}' and id=:a",array(":a"=>$memberno));
						$data3=array(
							"weid"=>$_W['uniacid'],
							"cid"=>$memberno,
							"userid"=>$userid,
							"groupid"=>$shopid,
							"usetype"=>2,
							"paytype"=>-1,
							"status"=>1,
							"startfee"=>$member['cash'],
							"cash"=>$order['paid_fee'],
							"endfee"=>$member['cash']+$order['paid_fee'],
							"out_trade_no"=>TIMESTAMP,
							"createtime"=>TIMESTAMP,
							"createdate"=>date("Y-m-d"),
							"remark"=>"订单".$order['out_trade_no']."退款"
						);
						pdo_insert("j_hmoney_recharge",$data3);
						pdo_update("j_hmoney_membercard",array("cash"=>$member['cash']+$order['paid_fee']),array("id"=>$memberno));
						pdo_update("j_hmoney_refund",array("status"=>1),array("id"=>$refundid));
					break;
					case 0:
					case 1:
						if($cfg['isbank']) {
                            $result = Bankpay_refund($cfg, $order['bank_trade_no'], $datarefund['out_refund_no'], $order['paid_fee'], $datarefund['fee']);
                            if ($result['status'] || $result['result_code']) {
                                pdo_delete("j_hmoney_refund", array("id" => $refundid));
                                return array("success" => false, "msg" => $result['message'] . $result['err_msg']);
                            }
                            pdo_update("j_hmoney_refund", array("status" => 1), array("id" => $refundid));
                        }elseif($cfg['isymf']){
                            $result = ymf_refund($order['bank_trade_no'],$shopid,$cfg);
                            if (!$result['success']) {
                                pdo_delete("j_hmoney_refund", array("id" => $refundid));
                                return array("success" => false, "msg" => $result['message'] . $result['err_msg']);
                            }
                            pdo_update("j_hmoney_refund", array("status" => 1), array("id" => $refundid));

						}else{
							$payParama=array(
								"appid"=>$shop['appid'] ? $shop['appid'] : $cfg['appid'],
								"pay_mchid"=>strval($shop['pay_mchid']) ? strval($shop['pay_mchid']) : strval($cfg['pay_mchid']),
								"pay_signkey"=>$shop['pay_signkey'] ? $shop['pay_signkey'] : $cfg['pay_signkey'],
								"pay_ip"=>$shop['pay_ip'] ? $shop['pay_ip'] : $cfg['pay_ip'],
								"sub_appid"=>$shop['sub_appid'] ? $shop['sub_appid'] : $cfg['sub_appid'],
								"sub_mch_id"=>$shop['sub_mch_id'] ? strval($shop['sub_mch_id']) : strval($cfg['sub_mch_id']),
								"apiclient_cert"=>'../attachment/j_hmoney/cert_2/'.$_W['uniacid']."/".$cfg['apiclient_cert'],
								"apiclient_key"=>'../attachment/j_hmoney/cert_2/'.$_W['uniacid']."/".$cfg['apiclient_key'],
								"app_id"=>$shop['app_id'] ? $shop['app_id'] : $cfg['app_id'],
								"appauthtoken"=>$shop['appauthtoken'] ? $shop['appauthtoken'] : $cfg['appauthtoken'],
								"alipay_cert"=>$shop['alipay_cert'] ? $shop['alipay_cert'] : $cfg['alipay_cert'],
								"alipay_key"=>$shop['alipay_key'] ? $shop['alipay_key'] : $cfg['alipay_key'],
								"alipay_store_id"=>$shop['alipay_store_id'] ,
							);
							$pageparama=array(
								"appid"=>$payParama['appid'],
								"mch_id"=>$payParama['pay_mchid'],
								"device_info"=>$userOpenid,
								"nonce_str"=>getNonceStr(),
								"out_trade_no"=>$datarefund['out_trade_no'],
								"out_refund_no"=>$datarefund['out_refund_no'],
								"total_fee"=>$order['paid_fee'],
								"refund_fee"=>$datarefund['fee'],
								"op_user_id"=>$userid,
								"app_id"=>$payParama['app_id'],
								"appauthtoken"=>$payParama['appauthtoken'],
								"alipay_cert"=>$payParama['alipay_cert'],
							);
							if($payParama['sub_appid'])$pageparama['sub_appid']=$payParama['sub_appid'];
							if($payParama['sub_mch_id'])$pageparama['sub_mch_id']=$payParama['sub_mch_id'];
							if($order['paytype']==1){
								$msg="已经通过支付宝退款";
								$postfee=$this->_2money($rfee);
								require_once '../addons/j_hmoney/plug/plug_alipay/F2fpay.php';
								$f2fpay = new F2fpay();
								$response = $f2fpay->refund($datarefund['out_trade_no'],$postfee,$pageparama);
								$temp=(array)$response;
								$result=(array)$temp['alipay_trade_refund_response'];
								if($result['code']=="10000"){
									pdo_update("j_hmoney_refund",array("status"=>1),array("id"=>$refundid));
								}else{
									pdo_delete("j_hmoney_refund",array("id"=>$refundid));
									return array("success"=>false,"msg"=>"失败:".$result['sub_msg']);
								}
							}else{
								unset($pageparama['alipay_cert']);
								unset($pageparama['appauthtoken']);
								unset($pageparama['app_id']);
								$sign=MakeSign($pageparama,$payParama['pay_signkey']);
								$pageparama['sign']=$sign;
								$xml = ToXml($pageparama);
								$pemary=array("cert"=>$payParama['apiclient_cert'],"key"=>$payParama['apiclient_key'],);
								$response =postXmlAndPemCurl($xml, "https://api.mch.weixin.qq.com/secapi/pay/refund", $pemary);
								$result=FromXml($response);
								if($result['result_code']!='SUCCESS'){
									pdo_delete("j_hmoney_refund",array("id"=>$refundid));
									return array("success"=>false,"msg"=>"失败:".$result['return_msg'].$result['err_code_des']);
								}
								pdo_update("j_hmoney_refund",array("status"=>1),array("id"=>$refundid));
							}
						}
					break;
			}
			if($isgetback){
				$goodslist=pdo_fetchall("SELECT * FROM ".tablename('j_hmoney_ordergoods')." WHERE weid='{$_W['uniacid']}' and orderid=:a ",array(":a"=>$orderid));
				foreach($goodslist as $row){
					$goods=pdo_fetch("SELECT * FROM " . tablename('j_hmoney_goods') . " WHERE weid = '{$_W['uniacid']}' and id=:a ",array(":a"=>$row["goodid"]));
					if($goods["store"]>-1){
						pdo_update("j_hmoney_goods",array("store"=>$goods["store"]+$row["num"]),array("id"=>$row["id"]));
					}
				}
			}
			pdo_update("j_hmoney_ordergoods",array("status"=>4,"num"=>0,"total_fee"=>0),array("orderid"=>$orderid));
			pdo_update("j_hmoney_order",array("status"=>4,"paid_fee"=>0,"refund_fee"=>$order['paid_fee'],"refundstatus"=>2),array("id"=>$orderid));
			goto refundend;
		}elseif($rtype==2){
			$fee=intval($rfee);
			$gid=$orderid;
			$goods=pdo_fetch("SELECT * FROM " . tablename('j_hmoney_ordergoods') . " WHERE weid = '{$_W['uniacid']}' and id=:a ",array(":a"=>$gid));
			$orderid=$goods['orderid'];
			if($goods['ispay']!=1)return array("success"=>false,"msg"=>"订单状态异常");
			if($goods['num']<$num)return array("success"=>false,"msg"=>"退货商品异常");
			$order=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_order')." WHERE weid = '{$_W['uniacid']}' and id=:a",array(":a"=>$orderid));
			$discount=(100-str_replace("%","",$order['discount']));
			$discountfee=intval($discount*intval($goods['price']*100)*0.01);
			$fee=$fee-$discountfee;
			$datarefund=array(
				"weid"=>$_W['uniacid'],
				"userid"=>$userid,
				"groupid"=>$shopid,
				"paytype"=>$paytype,
				"rtype"=>2,
				"createtime"=>TIMESTAMP,
				"createdate"=>date("Y-m-d"),
				"out_trade_no"=>$refun_out_no,
				"out_refund_no"=>TIMESTAMP.mt_rand(100,999),
				"remark"=>"商品退款：".$remark,
				"orderid"=>$orderid,
				"gid"=>$gid,
				"fee"=>$fee,
				"num"=>$num
			);
			pdo_insert("j_hmoney_refund",$datarefund);
			$refundid=pdo_insertid();
			if(!$refundid)return array("success"=>false,"msg"=>"生成退款单失败");
			$shop=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_group')." WHERE id =:a",array(":a"=>$shopid));
			$user=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_user') ." WHERE id =:a",array(":a"=>$userid));
			$mpaytype=$paytype;
			if($paytype==99){
				$mpaytype=$order["paytype"];
				pdo_update("j_hmoney_refund",array("paytype"=>$order["paytype"]),array("id"=>$refundid));
			};
			switch($mpaytype){
					case 2:
					case 3:
						pdo_update("j_hmoney_refund",array("status"=>1),array("id"=>$refundid));
					break;
					case 4:
						$memberno=$order['memberno'];
						$member=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_membercard')." WHERE weid = '{$_W['uniacid']}' and id=:a",array(":a"=>$memberno));
						$data3=array(
							"weid"=>$_W['uniacid'],
							"cid"=>$memberno,
							"userid"=>$userid,
							"groupid"=>$shopid,
							"usetype"=>2,
							"paytype"=>-1,
							"status"=>1,
							"startfee"=>$member['cash'],
							"cash"=>$fee,
							"endfee"=>$member['cash']+$fee,
							"out_trade_no"=>TIMESTAMP,
							"createtime"=>TIMESTAMP,
							"createdate"=>date("Y-m-d"),
							"remark"=>"订单".$order['out_trade_no']."退款"
						);
						pdo_insert("j_hmoney_recharge",$data3);
						pdo_update("j_hmoney_membercard",array("cash"=>$member['cash']+$fee),array("id"=>$memberno));
						pdo_update("j_hmoney_refund",array("status"=>1),array("id"=>$refundid));
					break;
					case 0:
					case 1:
						if($cfg['isbank']){
							$result=Bankpay_refund($cfg,$order['bank_trade_no'],$datarefund['out_refund_no'],$order['paid_fee'],$datarefund['fee']);
							if($result['status'] || $result['result_code']){
								pdo_delete("j_hmoney_refund",array("id"=>$refundid));
								return array("success"=>false,"msg"=>$result['message'].$result['err_msg']);
							}
							pdo_update("j_hmoney_refund",array("status"=>1),array("id"=>$refundid));
						}else{
							$payParama=array(
								"appid"=>$shop['appid'] ? $shop['appid'] : $cfg['appid'],
								"pay_mchid"=>strval($shop['pay_mchid']) ? strval($shop['pay_mchid']) : strval($cfg['pay_mchid']),
								"pay_signkey"=>$shop['pay_signkey'] ? $shop['pay_signkey'] : $cfg['pay_signkey'],
								"pay_ip"=>$shop['pay_ip'] ? $shop['pay_ip'] : $cfg['pay_ip'],
								"sub_appid"=>$shop['sub_appid'] ? $shop['sub_appid'] : $cfg['sub_appid'],
								"sub_mch_id"=>$shop['sub_mch_id'] ? strval($shop['sub_mch_id']) : strval($cfg['sub_mch_id']),
								"apiclient_cert"=>'../attachment/j_hmoney/cert_2/'.$_W['uniacid']."/".$cfg['apiclient_cert'],
								"apiclient_key"=>'../attachment/j_hmoney/cert_2/'.$_W['uniacid']."/".$cfg['apiclient_key'],
								"app_id"=>$shop['app_id'] ? $shop['app_id'] : $cfg['app_id'],
								"appauthtoken"=>$shop['appauthtoken'] ? $shop['appauthtoken'] : $cfg['appauthtoken'],
								"alipay_cert"=>$shop['alipay_cert'] ? $shop['alipay_cert'] : $cfg['alipay_cert'],
								"alipay_key"=>$shop['alipay_key'] ? $shop['alipay_key'] : $cfg['alipay_key'],
								"alipay_store_id"=>$shop['alipay_store_id'] ,
							);
							$pageparama=array(
								"appid"=>$payParama['appid'],
								"mch_id"=>$payParama['pay_mchid'],
								"device_info"=>$userOpenid,
								"nonce_str"=>getNonceStr(),
								"out_trade_no"=>$datarefund['out_trade_no'],
								"out_refund_no"=>$datarefund['out_refund_no'],
								"total_fee"=>$order['paid_fee'],
								"refund_fee"=>$datarefund['fee'],
								"op_user_id"=>$userid,
								"app_id"=>$payParama['app_id'],
								"appauthtoken"=>$payParama['appauthtoken'],
								"alipay_cert"=>$payParama['alipay_cert'],
							);
							if($payParama['sub_appid'])$pageparama['sub_appid']=$payParama['sub_appid'];
							if($payParama['sub_mch_id'])$pageparama['sub_mch_id']=$payParama['sub_mch_id'];
							if($order['paytype']==1){
								$msg="已经通过支付宝退款";
                                $postfee=$this->_2money($rfee);
								require_once '../addons/j_hmoney/plug/plug_alipay/F2fpay.php';
								$f2fpay = new F2fpay();
								$response = $f2fpay->refund($datarefund['out_trade_no'],$postfee,$pageparama);
								$temp=(array)$response;
								$result=(array)$temp['alipay_trade_refund_response'];
								if($result['code']=="10000"){
									pdo_update("j_hmoney_refund",array("status"=>1),array("id"=>$refundid));
								}else{
									pdo_delete("j_hmoney_refund",array("id"=>$refundid));
									return array("success"=>false,"msg"=>"失败:".$result['sub_msg'].$rfee);
								}
							}else{
								unset($pageparama['alipay_cert']);
								unset($pageparama['appauthtoken']);
								unset($pageparama['app_id']);
								$sign=MakeSign($pageparama,$payParama['pay_signkey']);
								$pageparama['sign']=$sign;
								$xml = ToXml($pageparama);
								$pemary=array("cert"=>$payParama['apiclient_cert'],"key"=>$payParama['apiclient_key'],);
								$response =postXmlAndPemCurl($xml, "https://api.mch.weixin.qq.com/secapi/pay/refund", $pemary);
								$result=FromXml($response);
								if($result['result_code']!='SUCCESS'){
									pdo_delete("j_hmoney_refund",array("id"=>$refundid));
									return array("success"=>false,"msg"=>"失败:".$result['return_msg'].$result['err_code_des']);
								}
								pdo_update("j_hmoney_refund",array("status"=>1),array("id"=>$refundid));
							}
						}
					break;
			}
			if($isgetback){
				$goodstore=pdo_fetch("SELECT * FROM " . tablename('j_hmoney_goods') . " WHERE weid = '{$_W['uniacid']}' and id=:a ",array(":a"=>$goods["goodid"]));
				if($goodstore["store"]>-1){
					pdo_update("j_hmoney_goods",array("store"=>$goodstore["store"]+$goods["num"]),array("id"=>$goods["goodid"]));
				}
			}
			$data=array(
				"status"=>$goods['num']>$num ? 3 : 4,
				"total_fee"=>($goods['num']-$num)*intval($goods['price']*100),
				"num"=>$goods['num']-$num,
			);
			pdo_update("j_hmoney_ordergoods",$data,array("id"=>$gid));
			$data=array(
				"num"=>$order['num']-$num,
				"paid_fee"=>$order['paid_fee']-$fee,
				"refund_fee"=>$order['refund_fee']+$fee,
				"status"=>$order['paid_fee']-$fee>0 ? 3 : 4, 
				"refundstatus"=>1,
			);
			pdo_update("j_hmoney_order",$data,array("id"=>$orderid));
			goto refundend;
		}
		/**/
		refundend:
		if($cfg['tempmsg_refunder']){
			$userlist=pdo_fetchall("SELECT openid FROM ".tablename('j_hmoney_user') ." WHERE pcate =:a and permission>1 and openid<>'' ",array(":a"=>$shopid));
			if($userlist){
				$temp=array(
					"first"=>array(
						"value"=>"【".$shop['companyname']."】有一笔退款",
						"color"=>"#FF0000"
					),
					"reason"=>array(
						"value"=>$datarefund['remark'],
						"color"=>"#FF0000"
					),
					"refund"=>array(
						"value"=>sprintf('%.2f',($datarefund['fee']*0.01)),
						"color"=>"#333333"
					),
					"remark"=>array(
						"value"=>"时间：".date("Y-m-d H:i")."\n处理人：".$user['realname']."\n单号：".$order['out_trade_no']."\n退款方式："._getPaytpye($mpaytype,$shopid),
						"color"=>"#FF0000"
					)
				);
				$acid=pdo_fetchcolumn("SELECT acid FROM ".tablename('account')." WHERE uniacid=:uniacid ",array(':uniacid'=>$_W['uniacid']));
				$acc = WeAccount::create($acid);
				foreach($userlist as $row){
					$acc->sendTplNotice($row['openid'],$cfg["tempmsg_refunder"],$temp,"","#FF0000");
				}
			}
		}
		return array("success"=>true,"refundid"=>$refundid);
	}
	
	public function _sendpack($openid,$record){
		global $_W;
		$cfg = $this->module['config'];
		$shop=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_group')." WHERE id =:a",array(":a"=>$record['groupid']));
 		$url='https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack';
        $pars = array();
		$pars['nonce_str'] =$this->getNonceStr();
		$pars['mch_billno'] =$shop['pay_mchid'].date('YmdHis').mt_rand(1000, 9999);
		$pars['mch_id']=$shop['pay_mchid'];
		$pars['wxappid'] =$shop['appid'];
		$pars['send_name'] =$shop['pay_name'];
		$pars['re_openid'] =$openid;
		$pars['total_amount'] =$record['content'];
		$pars['total_num'] =1;
		$pars['wishing'] ="礼品红包";
		$pars['client_ip'] =$cfg['pay_ip'];
		$pars['act_name'] =$shop['pay_name'];
		$pars['remark'] =$shop['pay_name'];
        ksort($pars, SORT_STRING);
        $string1='';
        foreach ($pars as $k => $v) {
            $string1 .= "{$k}={$v}&";
        }
        $string1 .= "key=".$shop['pay_signkey'];
        $pars['sign'] = strtoupper(md5($string1));
        $xml = array2xml($pars);
        $extras = array();
        $extras['CURLOPT_SSLCERT'] =IA_ROOT . '/attachment/j_hmoney/cert_2/'.$_W['uniacid']."/".$cfg['apiclient_cert'];
        $extras['CURLOPT_SSLKEY'] =IA_ROOT . '/attachment/j_hmoney/cert_2/'.$_W['uniacid']."/".$cfg['apiclient_key'];
		$procResult = null;
		load()->func('communication');
        $resp = ihttp_request($url, $xml, $extras);
        if (is_error($resp)) {
            $procResult = $resp;
        } else {
			$arr=json_decode(json_encode((array) simplexml_load_string($resp['content'])), true);
            $xml = '<?xml version="1.0" encoding="utf-8"?>' . $resp['content'];
            $dom = new \DOMDocument();
            if ($dom->loadXML($xml)){
                $xpath = new \DOMXPath($dom);
                $code = $xpath->evaluate('string(//xml/return_code)');
                $ret = $xpath->evaluate('string(//xml/result_code)');
                if (strtolower($code) == 'success' && strtolower($ret) == 'success') {
                    $procResult =  array('errno'=>0,'error'=>'success');
                } else {
                    $error = $xpath->evaluate('string(//xml/err_code_des)');
                    $procResult = array('errno'=>-2,'error'=>$error);
                }
            } else {
				$procResult = array('errno'=>-1,'error'=>'未知错误');				
            }
			$status=!$procResult['errno'] ? 1 : 0;
			$endtime=!$procResult['errno'] ? TIMESTAMP : 0 ;
			pdo_update('j_hmoney_giftrecord',array('endtime'=>$endtime,'openid'=>$openid,'isget'=>$status,'status'=>$status,'log'=>$procResult['error']),array('id'=>$record['id']));
        }
		return $procResult;
	}
    public function _2money($cash=0){
        return sprintf('%.2f',($cash*0.01));
    }
    public function _memberSoft($rechargeOrderid=0){
        global $_W;
        /*仅为会员系统中使用，订单中使用将会出现重复积分情况*/
        $cfg = $this->module['config'];
        $order=pdo_fetch("SELECT * FROM " . tablename('j_hmoney_recharge') . " WHERE id=:a ", array(":a" => $rechargeOrderid));
        if($order["status"]!=1)return false;
        $member = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE id=:a ", array(":a" => $order["cid"]));
        $shop = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_group') . " WHERE id=:a ", array(":a" => $order["groupid"]));
        $user = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_user') . " WHERE id=:a ", array(":a" => $order["userid"]));
        load()->func('communication');
        $percredit=$shop["creadit"]*100>0  ? $shop["creadit"] : $cfg["credit"];
        $allcredit=0;
        if($order["usetype"]==0) {
            if ($order["credit"] * 100 == 0 && $percredit) {
                $credit = intval($order["cash"] * $percredit);
                pdo_update("j_hmoney_recharge", array("credit" => $credit), array("id" => $rechargeOrderid));
                if ($member["uid"] || $member["openid"]) {
                    $uid = $member["uid"];
                    if (!$uid) {
                        load()->model('mc');
                        $uid = mc_openid2uid($member['openid']);
                        pdo_update("j_hmoney_membercard", array("uid" => $uid), array("id" => $member["id"]));
                    }
                    mc_credit_update($uid, "credit1", $credit, array("", "收银系统转移模块积分：" . $credit . ""));
                    $creditAry2 = mc_credit_fetch($uid, array('credit1'));
                    $allcredit = $creditAry2['credit1'];
                } else {
                    pdo_update("j_hmoney_membercard", array("credit" => $member["credit"] + $credit), array("id" => $member["id"]));
                    $allcredit = $member["credit"] + $credit;
                }
            }

            $temp = array(
                "first" => array(
                    "value" => "您在[" . $shop["companyname"] . "]充值成功",
                    "color" => "#333333",
                ),
                "keyword1" => array(
                    "value" => "+" . $this->_2money($order['cash']) . "元",
                    "color" => "#333333",
                ),
                "keyword2" => array(
                    "value" => $this->_2money($order['endfee']) . "元",
                    "color" => "#333333",
                ),
                "remark" => array(
                    "value" => "赠送金额：￥" . $this->_2money($order['gift']) . "元\n支付方式：￥" . _getPaytpye($order["paytype"]) . "\n卡号：" . $member['cardno'] . "\n该信息为系统信息，仅收银员接收",
                    "color" => "#333333",
                ),
            );
            $acid = pdo_fetchcolumn("SELECT acid FROM " . tablename('account') . " WHERE uniacid=:uniacid ", array(':uniacid' => $_W['uniacid']));
            $acc = WeAccount::create($acid);
            if ($user['openid']) $acc->sendTplNotice($user['openid'], $cfg["tempmsg_memberpay"], $temp, "", "#FF0000");
            $userlist = pdo_fetchall("SELECT openid FROM " . tablename('j_hmoney_user') . " WHERE  pcate=:a and permission=3 ", array(":a" => $order['groupid']));
            if (count($userlist)) {
                foreach ($userlist as $row) {
                    if ($row["openid"] == $user['openid']) continue;
                    $data = $acc->sendTplNotice($row["openid"], $cfg["tempmsg_memberpay"], $temp, "", "#FF0000");
                }
            }
            if ($member['openid']) {
                $str = "赠送金额：￥" . $this->_2money($order['gift']) . "元\n支付方式：￥" . _getPaytpye($order["paytype"]) . "\n卡号：" . $member['cardno'] . "\n";
                if ($credit) $str .= "获得积分：" . $credit . "\n总积分：" . $allcredit . "\n";
                $str .= "谢谢惠顾";
                $temp['remark']["value"] = $str;
                $data = $acc->sendTplNotice($member['openid'], $cfg["tempmsg_memberpay"], $temp, "", "#FF0000");
            }
        }elseif($order["usetype"]==2){

            $temp=array(
                "first"=>array(
                    "value"=>"您在[".$shop["companyname"]."]退款成功",
                    "color"=>"#333333",
                ),
                "keyword1"=>array(
                    "value"=>"+".$this->_2money($order['cash'])."元",
                    "color"=>"#333333",
                ),
                "keyword2"=>array(
                    "value"=>$this->_2money($order['endfee'])."元",
                    "color"=>"#333333",
                ),
                "remark"=>array(
                    "value"=>"系统备注：退款\n卡号：".$member['cardno']."\n该信息为系统信息，仅收银员接收",
                    "color"=>"#333333",
                ),
            );
            $acid=pdo_fetchcolumn("SELECT acid FROM ".tablename('account')." WHERE uniacid=:uniacid ",array(':uniacid'=>$_W['uniacid']));
            $acc = WeAccount::create($acid);
            if($user['openid'])$acc->sendTplNotice($user['openid'],$cfg["tempmsg_memberpay"],$temp,"","#FF0000");
            $userlist=pdo_fetchall("SELECT openid FROM ".tablename('j_hmoney_user')." WHERE  pcate=:a and permission=3 ",array(":a"=>$order['groupid']));
            if(count($userlist)){
                foreach($userlist as $row){
                    if($row["openid"]==$user['openid'])continue;
                    $data=$acc->sendTplNotice($row["openid"],$cfg["tempmsg_memberpay"],$temp,"","#FF0000");
                }
            }
            if($member['openid']){
                $str="系统备注：退款\n卡号：".$member['cardno']."\n谢谢惠顾";
                $temp['remark']["value"]=$str;
                $data=$acc->sendTplNotice($member['openid'],$cfg["tempmsg_memberpay"],$temp,"","#FF0000");
            }
        }elseif($order["usetype"]==1){
            $temp=array(
                "first"=>array(
                    "value"=>"您在[".$shop["companyname"]."]扣费成功",
                    "color"=>"#333333",
                ),
                "keyword1"=>array(
                    "value"=>"-".$this->_2money($order['cash'])."元",
                    "color"=>"#333333",
                ),
                "keyword2"=>array(
                    "value"=>$this->_2money($order['endfee'])."元",
                    "color"=>"#333333",
                ),
                "remark"=>array(
                    "value"=>"卡号：".$member['cardno']."\n该信息为系统信息，仅收银员接收",
                    "color"=>"#333333",
                ),
            );
            $acid=pdo_fetchcolumn("SELECT acid FROM ".tablename('account')." WHERE uniacid=:uniacid ",array(':uniacid'=>$_W['uniacid']));
            $acc = WeAccount::create($acid);
            if($user['openid'])$acc->sendTplNotice($user['openid'],$cfg["tempmsg_memberpay"],$temp,"","#FF0000");
            $userlist=pdo_fetchall("SELECT openid FROM ".tablename('j_hmoney_user')." WHERE  pcate=:a and permission=3 ",array(":a"=>$order['groupid']));
            if(count($userlist)){
                foreach($userlist as $row){
                    if($row["openid"]==$user['openid'])continue;
                    $data=$acc->sendTplNotice($row["openid"],$cfg["tempmsg_memberpay"],$temp,"","#FF0000");
                }
            }
            if($member['openid']){
                $temp['remark']["value"]="卡号：".$member['cardno']."\n谢谢惠顾";
                $data=$acc->sendTplNotice($member['openid'],$cfg["tempmsg_memberpay"],$temp,"","#FF0000");
            }
        }
        return true;
    }
    public function getCardTicket($card_id,$openid){
        global $_W,$_GPC;
        $data = pdo_fetch("SELECT * FROM ".tablename('j_hmoney_cardticket')." WHERE weid='".$_W['uniacid']."' " );
        load()->func('communication');
        if ($data['createtime'] < time()){
            $tokens= WeAccount::token();
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$tokens."&type=wx_card";
            $res = json_decode(httpGet($url));
            $now = TIMESTAMP;
            $now = intval($now) + 7200;
            $ticket = $res->ticket;
            $insert = array(
                'weid' => $_W['uniacid'],
                'createtime' => $now,
                'ticket' => $ticket,
            );
            if(empty($data)){
                pdo_insert('j_hmoney_cardticket',$insert);
            }else{
                pdo_update('j_hmoney_cardticket',$insert,array('id'=>$data['id']));
            }
        }else{
            $ticket=$data['ticket'];
        }
        $now = time();
        $timestamp = $now;
        $nonceStr = getNonceStr();
        $card_id = $card_id;
        $openid = $openid;
        $string = "card_id=$card_id&jsapi_ticket=$ticket&noncestr=$nonceStr$openid=$openid&timestamp=$timestamp";
        $arr = array($card_id,$ticket,$nonceStr,$openid,$timestamp);
        asort($arr, SORT_STRING);
        $sortString = "";
        foreach($arr as $temp){
            $sortString = $sortString.$temp;
        }
        $signature = sha1($sortString);
        $cardArry = array(
            'code' =>"",
            'openid' => $openid,
            'timestamp' => $now,
            'signature' => $signature,
            'cardId' => $card_id,
            'ticket' => $ticket,
            'nonceStr' => $nonceStr,
        );
        return $cardArry;
    }
}













